<template>
  <div>
    <div>
      <h1>更换头像</h1>
    </div>
     <el-upload
        class="avatar-uploader"
        :auto-upload="false"
        :on-change="fileChange"
        :show-file-list="false"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
  <div style="margin-top:40px;">
    <el-button type="primary" @click="toSel">选择图片</el-button>
    <el-button type="success" @click="toUpload">上传头像</el-button>
  </div>

  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

import { Plus } from '@element-plus/icons-vue'
import {userUpdateAvatarService}  from '@/api/use'
import mitt from '@/utils/mitt'
import {userStore} from '@/store/user'
let uStore=userStore();
const imageUrl = ref('') //存储缩略图路径
imageUrl.value=uStore.userObj.user_pic

let avatar=ref(); //存储图片流
// 文件上传的change事件的 选择的文件upfile.raw
    let fileChange=(upfile:any)=>{
        console.log(upfile.raw)//选择的文件
      // 根据选择的图片制作缩略图
        imageUrl.value=URL.createObjectURL(upfile.raw)
        // 将图片转为图片流
         // 基于 FileReader 读取图片做预览
          const reader = new FileReader()
          reader.readAsDataURL(upfile.raw)
          reader.onload = () => {
            // 读取的文件流  准备传给后台
            avatar.value = reader.result
          }
    }
    // 调用接口 传递 图片流文件
    let toUpload=async ()=>{
      let res=await userUpdateAvatarService(avatar.value);
      console.log(res,'-----33333333-------')
      if(res.code==0){
         ElMessage.success("更新头像成功")
          mitt.emit('senduser');
      }
    }

    // 点击选择图片按钮触发选择
    let toSel=()=>{
      // 获取原生的文件上传框
      // ts 类型断言  获取的元素 as  类型
      let myfile=document.querySelector(".el-upload__input") as HTMLInputElement ;
      myfile.click();
    }


</script>
<style lang="scss">
  .avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>